package com.hubei.controller;

import com.hubei.exception.CustomException;
import com.hubei.service.FileUploadService;
import org.apache.commons.fileupload.FileUpload;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class FileController {

    private FileUploadService uploadService;

    @RequestMapping("/file_upload.action")
    public String visitFile(){
        return "upload_file";
    }

    @RequestMapping("/save_upload.action")
    public String saveFile(HttpServletRequest request,MultipartFile file){
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        String realPath = application.getRealPath("/");
        realPath = realPath.replace("\\", "/")+"files/";
        if(file.getSize()!=0){
            String fileName = file.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            String type = fileName.substring(index);
            String newName = dealTime() + UUID.randomUUID() + type;
            File saveFile = new File(realPath + newName);
            try{
                file.transferTo(saveFile);
            }catch (Exception e){
                e.printStackTrace();
            }
            Map<String,String> map = new HashMap<>();
            map.put("name",fileName);
            map.put("path","/files"+newName);
            uploadService.saveFile(map);
        }else{
            throw new CustomException("没有文件数据提交！！");
        }
        return "redirect:/upload_list.action";
    }

    @RequestMapping("/upload_list.action")
    public String queryList(Model model){
        List<Map<String, String>> list = uploadService.queryUserList();
        model.addAttribute("fileList",list);
        return "upload_file";
    }

    private String dealTime(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
}
